<template>
  <inline-Modal :visible="visible" :showOk="false">
    <div class="wrapPage-container custom-knowledgeBase-container">
      <div class="screen-conditions-container">
        <ScreenConditions :isDataType="false">
          <template slot="conditions">
            <a-input
              v-model="condition.name"
              placeholder="请输入任务名称"
            ></a-input>
            <a-range-picker
              :placeholder="['开始日期', '开始日期']"
              format="YYYY-MM-DD"
              valueFormat="YYYY-MM-DD"
              v-model="condition.defaultTime"
              @change="search()"
            >
              <a-icon slot="suffixIcon" type="calendar" />
            </a-range-picker>
          </template>
          <template slot="operate">
            <a-button class="cu-btn-primary" icon="search" @click="search()">
              查询
            </a-button>
            <a-button class="cu-btn-filter" icon="reload" @click="reset()">
              重置
            </a-button>
            <a-button class="back-button" @click="goBack()">返回</a-button>
          </template>
        </ScreenConditions>
      </div>
      <div class="result-body-warp">
        <div class="drawing-container">
          <div class="header">{{ menuName }}</div>
          <div class="tree-container">
            <a-empty v-if="treeData.length == 0" />
            <a-tree
              v-else
              show-icon
              show-line
              v-model="checkedKeys"
              :expanded-keys="expandedKeys"
              :auto-expand-parent="autoExpandParent"
              :selected-keys="selectedKeys"
              :tree-data="treeData"
              :replaceFields="{
                children: 'childList',
                title: 'name',
                key: 'uuid',
              }"
              @expand="onExpand"
              @select="onSelect"
            >
              <template slot="title" slot-scope="{ name }">
                <div class="custom-tree-title-warp">
                  <div class="title" :title="name">
                    {{ name }}
                  </div>
                </div>
              </template>
            </a-tree>
          </div>
        </div>
        <div class="right-container">
          <div class="version-container">
            <a-button @click="handleSwap()">
              <a-icon type="swap" />
              展开/折叠
            </a-button>
          </div>
          <div class="main-container">
            <vxe-table
              size="small"
              border="inner"
              ref="xTree"
              align="center"
              height="99%"
              show-overflow
              show-header-overflow
              show-footer-overflow
              :data="tableData"
              :column-config="{ resizable: true }"
              :scroll-y="{ enabled: true }"
              :scroll-x="{ enabled: true }"
              :tree-config="{
                transform: true,
                rowField: 'uuid',
                parentField: 'parentId',
                childrenField: 'childList',
                reserve: true,
              }"
              :loading="loading"
              :row-config="{ keyField: 'uuid' }"
            >
              <vxe-column type="seq" width="80" title="序号"></vxe-column>
              <vxe-column field="name" title="任务名称" tree-node align="left">
              </vxe-column>
              <vxe-column field="duration" title="工期" width="100">
              </vxe-column>
              <vxe-column
                field="planStartTime"
                title="计划开始时间"
                width="180"
              >
              </vxe-column>
              <vxe-column field="planEndTime" title="计划完成时间" width="180">
              </vxe-column>
              <vxe-column field="major" title="关键节点" width="140">
                <template slot-scope="scope">
                  <span :class="filterMajorClass(scope.row.major)">
                    {{ scope.row.major | filterMajorNmae }}
                  </span>
                </template>
              </vxe-column>
              <vxe-column title="操作" fixed="right" width="180">
                <template slot-scope="scope">
                  <div class="text-button-group">
                    <a-button type="link" @click="handleDetail(scope.row)">
                      查看
                    </a-button>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </div>
    </div>
    <!-- 填报 -->
    <detailModal
      :visible.sync="detailModal.visible"
      :parameter="detailModal.row"
    ></detailModal>
  </inline-Modal>
</template>

<script>
import ScreenConditions from "@/components/extendCustom/ScreenConditions";
import detailModal from "./components/detailModal.vue";
import { addAttributeByKey, flatTreeData } from "@/utils/util.js";
import {
  getPlanControlVersion,
  getTreeList,
  getTreeListDraft,
  getTreeListHistory,
  getProgressTrackingList,
} from "@/api/progressManage";
export default {
  provide() {
    return {
      versionSource: () => this.currentVersion,
    };
  },
  components: {
    ScreenConditions,
    detailModal,
  },
  props: {
    visible: {
      type: Boolean,
      required: false,
    },
    parameter: {
      type: Object,
      default: () => {
        return {};
      },
    },
  },
  data() {
    return {
      //查询条件
      condition: {
        //项目
        tenantCode: "",
        //名称
        name: "",
        //时间
        defaultTime: [],
      },
      //左侧树
      treeLoading: false,
      treeData: [],
      expandedKeys: [],
      autoExpandParent: true,
      checkedKeys: [],
      selectedKeys: [],
      pageModule: "scheduleType.01",
      //版本信息
      currentVersion: {},
      //树节点
      currentTreeItem: {},
      //列表
      loading: false,
      tableData: [],
      //展开/折叠
      swap: false,
      //填报
      detailModal: {
        visible: false,
        row: {},
      },
    };
  },
  computed: {
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  filters: {
    //校验重大里程碑
    filterMajorNmae(val) {
      switch (Number(val)) {
        case 1:
          return "是";

        case 2:
          return "否";

        default:
          return "";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        if (val) {
          this.condition.tenantCode = this.parameter.proCode;
          this.getVersionData();
        }
      },
      immediate: true,
    },
  },
  methods: {
    //详情
    handleDetail(row) {
      this.detailModal.row = row;
      this.detailModal.visible = true;
    },
    //展开/折叠
    handleSwap() {
      this.swap = !this.swap;
      this.$refs.xTree.setAllTreeExpand(this.swap);
    },
    getTreeList,
    getTreeListDraft,
    getTreeListHistory,
    //查询版本号
    getVersionData() {
      let { tenantCode = "" } = this.condition;
      return new Promise((reslove, reject) => {
        getPlanControlVersion({
          proCode: tenantCode,
          type: this.pageModule,
          orgCode: "",
        })
          .then((res) => {
            this.currentVersion = res?.data ?? {};
            this.getTreeData();
            reslove();
          })
          .catch(() => {
            this.currentVersion = {};
            reject();
          });
      });
    },
    //查询一级节点
    getTreeData() {
      let { tenantCode = "" } = this.condition;
      let { uuid = "", status = "" } = this.currentVersion;
      if (!uuid) {
        this.selectedKeys = [];
        this.expandedKeys = [];
        this.currentTreeItem = {};
        this.treeData = [];
        return;
      }
      this.treeLoading = true;
      return new Promise((resolve, reject) => {
        let apiUrl = "";
        if (status == 4) {
          //正式
          apiUrl = "getTreeList";
        } else if (status == 5) {
          //历史记录
          apiUrl = "getTreeListHistory";
        } else {
          //草稿
          apiUrl = "getTreeListDraft";
        }
        this[apiUrl]({
          proCode: tenantCode,
          versionId: uuid,
          nodeType: this.pageModule,
          orgCode: "",
        })
          .then((res) => {
            let source = res?.data || [];
            let filterData = addAttributeByKey(
              null,
              "scopedSlots",
              { icon: "custom" },
              source,
              "childList"
            );
            this.treeData = filterData ?? [];
            this.treeData.length > 0 && this.getFirstTreeNode();
            resolve();
          })
          .catch((_) => {
            this.treeData = [];
            reject();
          })
          .finally((_) => {
            this.autoExpandParent = true;
            this.treeLoading = false;
          });
      });
    },

    //默认展开第一级节点
    getFirstTreeNode() {
      let { treeData } = this;
      let flatData = flatTreeData(treeData, "childList");
      let item = flatData.find((v) => !v.childList || v.childList.length == 0);
      this.expandedKeys = [item.uuid];
      this.selectedKeys = [item.uuid];
      this.currentTreeItem = item;
      this.getData();
    },

    //展开
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },

    //树选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.currentTreeItem = info.node.dataRef;
      this.getData();
    },

    //查询数据
    getData() {
      let { uuid = "" } = this.currentVersion;
      let { tenantCode = "", defaultTime } = this.condition;
      this.loading = true;
      getProgressTrackingList({
        showAll: 1,
        versionId: uuid,
        parentId: this.currentTreeItem?.uuid ?? "",
        proCode: tenantCode,
        orgCode: "",
        name: "",
        startDate: defaultTime?.[0] ?? "",
        endDate: defaultTime?.[1] ?? "",
      })
        .then((res) => {
          this.tableData = res.data?.dataList ?? [];
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally(() => {
          this.loading = false;
          this.swap = false;
        });
    },

    //搜索
    search() {
      this.getData();
    },

    //重置
    reset() {
      this.condition.name = "";
      this.condition.defaultTime = [];
      this.getData();
    },

    //校验状态
    filterStatusClass(val) {
      switch (Number(val)) {
        case -1:
          return "default";

        case 0:
          return "default";

        case 1:
          return "warning";

        case 2:
          return "progress";

        case 3:
          return "reject";

        case 4:
          return "success";

        case 5:
          return "place-file";

        default:
          return "";
      }
    },

    //返回
    goBack() {
      this.$parent.getTableData();
      this.$emit("update:visible", false);
    },

    filterMajorClass(val) {
      switch (Number(val)) {
        case 1:
          return "correct";

        case 2:
          return "deny";

        default:
          return "";
      }
    },
  },
};
</script>

<style lang="less" scoped>
.modal-full-layout {
  background-color: #f0f2f5;
  /deep/.header {
    display: none;
  }
  /deep/.main {
    padding: 0;
    overflow: hidden !important;
  }
  .wrapPage-container {
    height: 100%;
    overflow: hidden;
    .back-button {
      position: absolute;
      right: 16px;
    }
    .result-body-warp {
      .right-container {
        .version-container {
          display: flex;
          justify-content: flex-end;
          box-sizing: border-box;
          padding: 14px 20px 14px 20px;
          /deep/.anticon-swap {
            transform: rotate(90deg);
          }
        }
        .main-container {
          flex: 1;
        }
      }
    }
  }
}
</style>
